﻿const config = require('./config');
require('colors');
const path = require('path');
const express = require('express');
require('./middlewares/mongoose_log'); // 打印 mongodb 查询日志
const compress = require('compression');
const bodyParser = require('body-parser');
const requestLog = require('./middlewares/request_log');
const renderMiddleware = require('./middlewares/render');
const logger = require('./common/logger');
const cluster = require("cluster");
const numCPUs = require('os').cpus().length;
const api_router = require('./web_api_router');
// https   本地测试暂时引入http模块  服务器环境更换为https模块
const https = require('http');
const fs = require('fs');
// options https证书
// const options = {
//     key: fs.readFileSync('./ssl/214128300560989.key'),
//     cert: fs.readFileSync('./ssl/214128300560989.pem')
// };
// 静态文件目录
const staticDir = path.join(__dirname, 'wiki');
const urlinfo = require('url').parse(config.host);
config.hostname = urlinfo.hostname || config.host;
const app = express();
app.use(bodyParser.json({ limit: '1mb' }));  //body-parser 解析json格式数据
app.use(bodyParser.urlencoded({            //此项必须在 bodyParser.json 下面,为参数编码
    extended: false
}));
//权限审核中间件
const Authentication = require("./middlewares/authentication");

app.set('trust proxy', 1) // trust first proxy
// Request logger。请求时间
app.use(requestLog);
if (config.debug) {
    // 渲染时间
    app.use(renderMiddleware.render);
}
//提供静态服务
app.use('/img', express.static("./Images"));
app.use("/src", express.static(staticDir));

// 通用的中间件
app.use(require('response-time')());

//app.use(helmet.frameguard('sameorigin'));
app.use(require('method-override')());
app.use(compress());

//设置ajax前端请求数据跨域处理

app.set('view cache', true);


//设置模板
app.set('view engine', 'ejs')

// error handler
app.use(function (err, req, res, next) {
    logger.error(err);
    return res.status(500).send('500 status');
});

app.all('*', function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By", ' 3.2.1')
    if (req.method == "OPTIONS") res.send(200); /*让options请求快速返回*/
    else next();
});

// routes  需要可以自己添加路由器
app.use("/", require("./router/login"))

process.on('uncaughtException', function (err) {
    //打印出错误
    console.log(err);
    //打印出错误的调用栈方便调试
    console.log(err.stack);
});
var a;
// if (cluster.isMaster) {
//     console.log(`主进程 ${process.pid} 正在运行`);
//     // 衍生工作进程。
//     for (let i = 0; i < numCPUs; i++) {
//         cluster.fork();
//     }
//     cluster.on('exit', (worker, code, signal) => {
//         console.log(`工作进程 ${worker.process.pid} 已退出`);
//     });
// } else {
//     // 工作进程可以共享任何 TCP 连接。
//     // 在本例子中，共享的是一个 HTTP 服务器。
    
//     console.log(`工作进程 ${process.pid} 已启动`);
// };
if (!module.parent) {
    a = https.createServer(app)
    a.listen(config.port, function () {
        logger.info('xcxservice listening on port', config.port);
        logger.info('God bless love....');
        logger.info('You can debug your app with http://' + config.hostname + ':' + config.port);
        logger.info('');
    });
};
//创建websocket
var createsocket = require("./websocket/websockets");
createsocket.init(a);


module.exports = app;
